<template>
  <div style="padding-top: 110px">
    <div class="app-title-container title-position">
      <modules-title titleName="稳定性箱变更">
        <template slot="btn">
          <el-button
            class="filter-item"
            type="primary"
            icon="el-icon-plus"
            size="small"
            v-hasPermi="{ v: ['wendingxingxiang:change'] }"
            @click="handleCreate"
            >创建变更申请
          </el-button>
        </template>
      </modules-title>
    </div>
    <div style="padding: 20px" class="change">
      <el-form :inline="true">
        <!-- <el-form-item label="">
          <el-select
            v-model="all"
            placeholder="全部"
            clearable
            size="small"
            @change="changeStatus()"
          >
            <el-option
              v-for="(item, index) in status"
              :key="index"
              :label="item.label"
              :value="item.id"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="状态">
          <el-select
            v-model="all1"
            placeholder="全部"
            clearable
            size="small"
          >
            <el-option
              v-for="(item, index) in v2"
              :key="index"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="申请人" style="margin-left: 40px">
          <el-select
            v-model="apply"
            placeholder="申请人"
            clearable
            size="small"
          >
            <el-option
              v-for="(item, index) in v1"
              :key="index"
              :label="item.creator_name"
              :value="item.creator_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="关键字搜索" style="margin-left: 40px">
          <el-input
            v-model="name"
            placeholder="请输入关键字"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item style="margin-left: 40px">
          <el-button
            type="primary"
            icon="el-icon-search"
            size="small"
            @click="handleQuery"
            >搜索
          </el-button>
          <el-button
            icon="el-icon-refresh"
            plain
            size="small"
            @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <!-- 表格 -->
      <el-table
        :data="tableData"
        size="medium"
        border
        @row-click="rowClick"
        :cell-style="cellStyle"
      >
        <el-table-column prop="change_box_no" label="变更申请编号" align="center" width="140">
          <template slot-scope="scope">
            {{ scope.row.check_info.change_box_no }}
          </template>
        </el-table-column>
        <el-table-column
          label="原稳定性箱编号"
          align="center"
          prop="instrument_no"
          width="150"
        >
          <template slot-scope="scope">
            {{ scope.row.check_info.old_instrument.instrument_no }}
          </template>
        </el-table-column>
        <el-table-column
          label="原稳定性箱名称"
          align="center"
          prop='instrument_name'
        >
          <template slot-scope="scope">
            {{ scope.row.check_info.old_instrument.instrument_name }}
          </template>
        </el-table-column>
        <el-table-column
          label="更换后稳定性箱编号"
          align="center"
          prop="instrument_no"
          width="150"
        >
          <template slot-scope="scope">
            {{ scope.row.check_info.new_instrument.instrument_no }}
          </template>
        </el-table-column>
        <el-table-column
          label="更换后稳定性箱名称"
          align="center"
          prop='instrument_name'
        >
          <template slot-scope="scope">
            {{ scope.row.check_info.new_instrument.instrument_name }}
          </template>
        </el-table-column>
        <el-table-column
          label="放/取样计划编号"
          align="center"
          prop="plan_no"
          width="160"
        >
          <template slot-scope="scope">
            {{ scope.row.check_info.plan_no }}
          </template>
        </el-table-column>
        <el-table-column
          prop="sample_name"
          label="样品名称"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.check_info.sample_info.sample_name }}
          </template>
        </el-table-column>
        <el-table-column  label="放置条件" align="center" prop="place_conditions_name">
          <template slot-scope="scope">
            {{ scope.row.check_info.place_conditions.place_conditions_name }}
          </template>
        </el-table-column>
        <el-table-column label="申请人" align="center" prop="creator_name" width="100">
          <template slot-scope="scope">
            {{ scope.row.check_info.creator_name }}
          </template>
        </el-table-column>
        <el-table-column  label="申请时间" align="center" prop="created_at" width="160">
          <template slot-scope="scope">
            {{ scope.row.check_info.created_at }}
          </template>
        </el-table-column>
        <el-table-column prop="change_status" label="状态" align="center" width="80">
            <template slot-scope="scope">
              <p>{{scope.row.check_info.change_status}}</p>
              <!-- <p class="status-color5" v-if="scope.row.check_info.change_status=='已确定'">已确定</p>
              <p class="status-color5" v-if="scope.row.check_info.change_status=='已结束'">已结束</p>
              <p class="status-color5" v-if="scope.row.check_info.change_status=='审批'">待审批</p> -->
            </template>
        </el-table-column>
        <el-table-column label="操作" align="left"
            header-align="center"
            width="80">
          <template #default="{ row }">
            <!-- <el-button
              type="text"
              icon="el-icon-view"
              @click="handlDeltails(row.id)"
              >查看详情</el-button
            > -->
            <el-button
              type="text"
              v-if="row.check_info.instrument_check.Cancelable==true&&row.check_info.instrument_check.check_creator_id==userId"
              @click="undo(row.check_info.instrument_check.id)"
              >撤销</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        style="
          display: flex;
          justify-content: flex-end;
          padding-bottom: 0px !important;
        "
        :total="total"
        :page.sync="pages.pageNum"
        :limit.sync="pages.pageSize"
        @pagination="afreshList"
      />
    </div>
    <el-dialog
      title="变更确认"
      :visible.sync="openC"
      width="500px"
      append-to-body
      :destroy-on-close="true"
      :before-close="handleClose"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="结论" prop="radio">
          <el-radio-group v-model="form.radio">
                <el-radio :label=item.id v-for="(item,index) in buttons" :key="index">{{item.value}}</el-radio>
          </el-radio-group>

          <!-- <el-radio v-model="form.radio" label="1">确认变更</el-radio>
          <el-radio v-model="form.radio" label="2">取消变更</el-radio> -->
        </el-form-item>
        <el-form-item label="处理意见" prop="suggestion">
          <el-input
            v-model="form.suggestion"
            type="textarea"
            placeholder="请输入处理意见"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button plain @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="cSubmitForm">提交</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="稳定性箱变更确认申请"
      :visible.sync="open"
      append-to-body
      :destroy-on-close="true"
      :before-close="handleClose"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="125px">
        <el-form-item label="变更前设备" prop="qualityq">
              <el-select style="width:100%" v-model="form.qualityq" filterable placeholder="变更前设备(来自已放样的设备)" clearable @change="changeQ()"
                size="small">
                <el-option v-for="(item, index) in values1" :key="index" :label="item.instrument_no+'   '+item.instrument_name"
                  :value="item.instrument_id" :disabled="item.instrument_id==form.qualityh" />
              </el-select>
            </el-form-item>
        <el-form-item label="变更原因" prop="reason">
          <el-input
            v-model="form.reason"
            type="textarea"
            placeholder="请输入变更原因"
          ></el-input>
        </el-form-item>
        <el-form-item label="变更后设备" prop="qualityh">
            <el-select style="width:100%" v-model="form.qualityh" filterable placeholder="变更后设备" clearable @change="changeH()"
            size="small">
            <el-option v-for="(item, index) in values" :key="index" :label="item.instrument_no+'   '+item.instrument_name"
                :value="item.instrument_id" :disabled="item.instrument_id==form.qualityq" />
            </el-select>
        </el-form-item>
         <el-form-item label="影响放/取样计划" prop="select">
           <el-table
                ref="multipleTable"
                :data="tableDataD"
                border
                tooltip-effect="dark"
                style="width: 100%"
                @selection-change="handleSelectionChange">
                <el-table-column
                prop="id"
                type="selection"
                align="center"
                >
                </el-table-column>
                <el-table-column
                label="计划编号"
                align="center"
                prop="plan_no"
                >
                <template slot-scope="scope">{{ scope.row.plan_no }}</template>
                </el-table-column>
                <el-table-column
                prop="sample_name"
                label="样品名称"
                align="center"
                >
                <template slot-scope="scope">
                   {{scope.row.sample_info.sample_name}}
                </template>
                </el-table-column>
                 <el-table-column
                prop="name"
                label="稳定性考察类型"
                align="center"
                >
                <template slot-scope="scope">
                   {{scope.row.inspect_type.inspect_type_name}}
                </template>
                </el-table-column>
                 <el-table-column
                prop="place_conditions_name"
                label="放置条件"
                align="center"
                >
                <template slot-scope="scope">
                   {{scope.row.place_conditions.place_conditions_name}}
                </template>
                </el-table-column>
                 <el-table-column
                prop="stability_scheme_name"
                label="稳定性方案"
                align="center"
                >
                </el-table-column>
                <el-table-column
                prop="project_name"
                label="项目名称"
                align="center"
                >
                </el-table-column>
            </el-table>
        </el-form-item>
         <el-form-item label="附件：" prop="file">
            <upload-select ref="upload" :edit-list="filelist" :project-data="{project_id: 'require',validation: 1}" @selectSuccess="selectSuccess" @uploadSuccess="uploadSuccess" @deleteSuccess="deleteSuccess" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button plain @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  changeList,
  statusSelect,
  applyPepole,
  oldList,
  getPlan,
  qUpdate,
  changeCreate,
  undoX
} from "@/api/stability/change";
import {
  instrument
} from "@/api/stability/giveUp";
export default {
  data() {
    let reason = (rule, value, callback) => {
      if (this.form.reason != '') {
        if(this.form.reason.split(" ").join("").length == 0){
          callback(new Error("变更原因不能全是空格"));
        }else{
          callback();
        }
      } else {
        callback(new Error("变更原因不能为空"));
      }
    };
    let select = (rule, value, callback) => {
      if (this.plan.length > 0) {
        callback();
      } else {
        callback(new Error("请至少选择一个放取样计划"));
      }
  }
  var filePass = (rule, value, callback) => {
      if (this.objData.fileList.length > 0 || this.objData.newFileList.length > 0) {
          callback()
        } else {
          callback(new Error('请上传附件'))
        }
    }  
    return {
      filelist:[],
      buttons:[],
      values1:[],
      apply:'',
      tableDataD:[],
       values: [
        {
          instrument_id:'1',
          instrument_name:'宝箱1',
          instrument_no:'1',
          brand_model:'1',
          attrs:'1',
          locker_id:'1',
          locker_name:'cdd'
        },
        {
          instrument_id:'2',
          instrument_name:'宝箱2',
          instrument_no:'2',
          brand_model:'1',
          attrs:'1',
          locker_id:'1',
          locker_name:'cdd1'
        },
      ],
      openC: false,
      all: "0",
      all1: "",
      status1: "0",
      inspect_type: "",
      place_condition: "",
      name: "",
      pages: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      status: [
        {
          id: "0",
          label: "全部",
        },
        // {
        //   id: "1",
        //   label: "我处理的",
        // },
        {
          id: "2",
          label: "我发起的",
        },
      ],
      tableData: [
      
      ],
      open: false,
      openF: false,
      form: {
        radio:'',
        qualityq:'',
        qualityh:'',
        reason:'',
        suggestion:''
      },
      rules: {
       radio:[{required: true, message: "请选择", trigger: "change"}],
       suggestion: [{ required: true, message: "请输入处理意见", trigger: "blur" }],
       qualityq: [{ required: true, message: "请选择变更前设备", trigger: "change" }],
       qualityh: [{ required: true, message: "请选择变更后设备", trigger: "change" }],
       reason: [{ required: true, validator:reason, trigger: "blur" }],
       select:[{required:true,validator: select}],
       file: [
          {
            required: true,
            validator: filePass,
            trigger: 'change'
          }
        ],
      },
      checkList: [],
      v1: [],
      v2: [],
      id:'',
      plan:[],
      qualityq:[],
      qualityh:[],
      userId:'',
      objData: {
          fileList: [],
          newFileList: []
        },
    };
  },
   beforeRouteEnter(to, from, next) {
    to.params.refresh = from.params.refresh;
    next();
  },
  activated() {
    if (this.$route.params.refresh) {
      this.getList();
    }
  },
  //是计算属性，也可以理解为一个方法。
  computed: {},
  //属性是手动定义的所需监听的值
  watch: {},
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.userId = this.$store.getters.userInfo.user.id
    this.getSelectStatus();
    this.getSelectApply();
    this.getList();
    this.getinstrument()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {},
  //是Vue实例对象上绑定的方法，供当前Vue组件作用域内使用，
  methods: {
    deleteSuccess() {
      // this.formData.enclosure = this.$refs.upload.emitFileList()
    },
    // 附件上传成功
    uploadSuccess(file) {
      // this.formData.enclosure = this.$refs.upload.emitFileList()
    },
    selectSuccess(obj) {
        this.objData = obj
        if (obj.fileList.length > 0 || obj.newFileList.length > 0) {
          this.$nextTick(_ => {
            this.$refs.form.clearValidate('file')
          })
        }
      },
    undo(flow_id){
      this.$confirm('此操作将撤销此申请, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let data={
            flow_id:flow_id,
            model_type:'ExchangeStability'
          }
          undoX(data).then(res=>{
            if(res.code==200){
              this.$message.success('撤销成功')
              this.getList();
            }
          })
        }).catch(() => {
          
        });
    },
    // c(){
    //   console.log(this.all1)
    //   if(this.all1=='待审批'){
    //     this.all1 = '审批'
    //   }
    // },
    getinstrument(){
      let data = {
        subTypes: [],
        key: ''
      }
       instrument(data).then(res=>{
          if(res.code==200){
            console.log(res.data)
            this.values = res.data
          }
       })
    },
    changeQ(){
      if(this.form.qualityq){
         getPlan(this.form.qualityq).then(res=>{
          if(res.code==200){
            console.log(res.data)
            this.tableDataD = res.data
            this.$refs.multipleTable.toggleAllSelection()
          }
        })
        this.values1.forEach(item=>{
          if(item.instrument_id==this.form.qualityq){
            this.qualityq = {
              instrument_id:item.instrument_id,
              instrument_name:item.instrument_name,
              instrument_no:item.instrument_no,
              brand_model:item.brand_model,
              attrs:item.attrs,
              locker_id:item.locker_id,
              locker_name:item.locker_name
            }
          }
        })
      }else{
        this.tableDataD=[]
      }
     
    },
    changeH(){
      this.values.forEach(item=>{
        if(item.instrument_id==this.form.qualityh){
          this.qualityh = {
            instrument_id:item.instrument_id,
            instrument_name:item.instrument_name,
            instrument_no:item.instrument_no,
            brand_model:item.brand_model,
            attrs:item.attrs,
            locker_id:item.locker_id,
            locker_name:item.locker_name
          }
        }
      })
    },
    handleSelectionChange(val){
      console.log(val)
      this.plan=[]
      val.forEach(item=>{
         let obj = {
              stability_scheme_id:item.stability_scheme_id,
              stability_scheme_name:item.stability_scheme_name,
              project_id:item.project_id,
              project_name:item.project_name,
              project_no:item.project_no,
              project_leader_id:item.project_leader_id,
              project_leader_name:item.project_leader_name,
              inspect_type:item.inspect_type,
              place_conditions:item.place_conditions,
              plan_id:item.id,
              plan_no:item.plan_no,
              sample_info:item.sample_info,
              sample_batch:item.sample_batch,
              sample_attrs:item.sample_attrs,
              packaging_nu:item.packaging_nu,
              packaging_nu_unit:item.packaging_nu_unit,
              packaging_unit:item.packaging_unit,
              producer:item.producer
            }
        this.plan.push(obj)
      })
    },
    handleChange(id,row) {
      this.buttons=[]
      console.log(row.check_info.instrument_check.next)
      if(row.check_info.instrument_check.next!=null){
        let buttons = row.check_info.instrument_check.next[0].Buttons
        buttons.forEach(item=>{
          if(item.Type=='Next'){
            let obj = {
              value:item.Name,
              id:'1'
            }  
            this.buttons.push(obj)
          }else if(item.Type=='Refuse'){
            let obj = {
              value:item.Name,
              id:'2'
            }  
            this.buttons.push(obj)
          }else if(item.Type=='Reject'){
            let obj = {
              value:item.Name,
              id:'3'
            }  
            this.buttons.push(obj)
          }else{
            let obj = {
              value:item.Name,
              id:'4'
            }  
            this.buttons.push(obj)
          }
          console.log(this.buttons)
        })
      }
      this.openC = true;
      this.form.radio='1'
      this.id = id
    },
    cSubmitForm() {
      let data = {
        id:this.id,
        status:Number(this.form.radio),
        deal_advice:this.form.suggestion
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
           qUpdate(data).then(res=>{
            if(res.code==200){
              this.openC = false;
              this.$message.success('修改成功')
              this.getList();
              this.handleClose()
            }else{
              this.$message.error(res.msg)
            }
          })
        }
      })
    },
    handleCreate() {
        this.open = true
        oldList().then(res=>{
          if(res.code==200){
            this.values1 = res.data
          }
        })
        this.form= {
        radio:'',
        qualityq:'',
        qualityh:'',
        reason:'',
        suggestion:''
      }
      this.tableDataD=[]
      this.$nextTick(() => {
        this.$refs.form.clearValidate('qualityq')
        this.$refs.form.clearValidate('qualityh')
      })
    },
    cellStyle(data) {
      return "cursor:pointer;";
    },
    rowClick(row, column) {
      console.log(column)
      if (column.label == "操作") return;
      console.log(row.check_info.id);
      this.$router.push({
        path: "/stability/change/details",
        query: {
          id: row.check_info.id,
        },
      });
    },
    changeStatus() {
      // this.status1 = this.all;
      // if (this.all == "") {
      //   this.status1 = "-1";
      // }
    },
    handleQuery() {
      this.pages={
        pageNum: 1,
        pageSize: 10,
      }
      this.getList();
    },
    afreshList() {
      this.getList();
    },
    getSelectStatus() {
      statusSelect().then((res) => {
        if (res.code == 200) {
          // console.log(res.data);
          this.v2 = res.data;
        }
      });
    },
    getSelectApply() {
      applyPepole().then((res) => {
        if (res.code == 200) {
          console.log(res.data);
          this.v1 = res.data;
        }
      });
    },
    getList() {
      // let all1=''
      // if(this.all1=='待审批'){
      //   all1 = '审批'
      // }else{
      //   all1 = this.all1
      // }
      let data = {
        pager: {
          limit: this.pages.pageSize,
          skip: this.pages.pageNum,
        },
        apply_type:Number(this.all),
        status: this.all1,
        creator_id:this.apply,
        select_str:this.name 
      };
      changeList(data).then((res) => {
        if (res.code == 200) {
          this.tableData = res.data.data;
          this.total = res.data.total;
        }
      });
    },
    resetQuery() {
     this.pages={
        pageSize:10,
        pageNum:1,
      }
      this.all='',
      this.all1='',
      this.apply='',
      this.name=''
      this.getList()
    },
    q() {
      this.open = true;
    },
    f() {
      this.openF = true;
    },
    handleClose() {
      this.openC = false;
      this.open = false;
      this.form= {
        radio:'',
        qualityq:'',
        qualityh:'',
        reason:'',
        suggestion:''
      }
      this.tableDataD=[]
    },
    submitForm() {
      this.$refs.upload.saveFile().then((dataList) => {
          this.filelist = dataList[0]
           this.$refs.form.validate((valid) => {
              if (valid) {
                let data = {
                  old_instrument:this.qualityq,
                  new_instrument:this.qualityh,
                  change_reason:this.form.reason,
                  info:this.plan,
                  enclosure:this.filelist
                }
                changeCreate(data).then(res=>{
                  if(res.code==200){
                    this.$message.success('创建成功')
                    this.open = false;
                    this.getList();
                  }
                })
              }
            })
         })
      // this.$refs.form.validate((valid) => {
      //   if (valid) {
      //     let data = {
      //       old_instrument:this.qualityq,
      //       new_instrument:this.qualityh,
      //       change_reason:this.form.reason,
      //       info:this.plan
      //     }
      //     changeCreate(data).then(res=>{
      //       if(res.code==200){
      //         this.$message.success('创建成功')
      //         this.open = false;
      //         this.getList();
      //       }
      //     })
      //   }
      // })
    },
    //查看详情
    handlDeltails(id) {
      // this.$router.push("/stability/management/details");
      this.$router.push({
        path: "/stability/change/details",
        query: {
          id: id,
        },
      });
    },
  },
};
</script>
<style lang="scss">
/* @import url(); 引入css类 */
::v-deep .el-button--text {
  padding: 0;
  margin: 0 !important;
  margin-right: 10px !important ;
}
.change{
 .el-table{
      max-height: calc( 100vh - 130px);
      // .el-table__header{
      //   .cell{
      //   }
      // }
      // .el-table__body{
      //   .el-table__row{
      //     height: 60px;
      //     .cell{
      //     }
      //   }
      // }
      .el-table__body-wrapper{
        overflow-y: auto;
        max-height: calc( 100vh - 320px);
      }
    }    
}
</style>